package com.example.teaching_server.service;

import com.example.teaching_server.dto.CreateSubThemeRequest;
import com.example.teaching_server.dto.ThemeDTO;
import com.example.teaching_server.entity.EducationTheme;
import com.example.teaching_server.repository.EducationThemeRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 教育主题管理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class ThemeService {

    private final EducationThemeRepository educationThemeRepository;

    /**
     * 获取所有主题（每个父主题只返回前3个子主题）
     */
    @Transactional(readOnly = true)
    public List<ThemeDTO> getThemes() {
        log.debug("获取所有主题（限制每个父主题3个子主题）");

        List<EducationTheme> mainThemes = educationThemeRepository.findByParentIsNullOrderBySortOrderAsc();
        return mainThemes.stream()
                .map(this::convertToThemeDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据父主题ID获取该父主题和所有子主题
     */
    @Transactional(readOnly = true)
    public ThemeDTO getThemeWithAllSubThemes(Long parentId) {
        log.debug("获取主题及其所有子主题: parentId={}", parentId);

        validateParentId(parentId);

        EducationTheme parentTheme = educationThemeRepository.findById(parentId)
                .orElseThrow(() -> {
                    log.warn("父主题不存在: parentId={}", parentId);
                    return new RuntimeException("父主题不存在");
                });

        ThemeDTO themeDTO = convertToThemeDTO(parentTheme);
        List<EducationTheme> allSubThemes = educationThemeRepository
                .findByParentIdOrderBySortOrderAsc(parentId);

        List<ThemeDTO.SubThemeDTO> allSubThemeDTOs = allSubThemes.stream()
                .map(this::convertToSubThemeDTO)
                .collect(Collectors.toList());

        themeDTO.setSubThemes(allSubThemeDTOs);
        return themeDTO;
    }

    /**
     * 创建子主题
     */
    public ThemeDTO.SubThemeDTO createSubTheme(CreateSubThemeRequest request) {
        log.info("创建子主题: parentId={}, name={}", request.getParentId(), request.getName());

        validateCreateSubThemeRequest(request);

        try {
            EducationTheme parentTheme = educationThemeRepository.findById(request.getParentId())
                    .orElseThrow(() -> {
                        log.warn("父主题不存在: parentId={}", request.getParentId());
                        return new RuntimeException("父主题不存在");
                    });

            EducationTheme subTheme = buildSubThemeEntity(request, parentTheme);
            EducationTheme savedSubTheme = educationThemeRepository.save(subTheme);

            log.info("子主题创建成功: subThemeId={}", savedSubTheme.getId());
            return convertToSubThemeDTO(savedSubTheme);

        } catch (Exception e) {
            log.error("创建子主题失败: parentId={}, name={}", request.getParentId(), request.getName(), e);
            throw new RuntimeException("创建子主题失败: " + e.getMessage());
        }
    }

    /**
     * 转换主主题DTO（只返回前3个子主题）
     */
    private ThemeDTO convertToThemeDTO(EducationTheme theme) {
        ThemeDTO dto = new ThemeDTO();
        dto.setId(theme.getId());
        dto.setName(theme.getName());
        dto.setLabel(theme.getLabel());
        dto.setDescription(theme.getDescription());
        dto.setCoverImage(theme.getCoverImage());
        dto.setSortOrder(theme.getSortOrder());

        List<ThemeDTO.SubThemeDTO> subThemes = educationThemeRepository
                .findByParentIdOrderBySortOrderAsc(theme.getId())
                .stream()
                .limit(3)
                .map(this::convertToSubThemeDTO)
                .collect(Collectors.toList());

        dto.setSubThemes(subThemes);
        return dto;
    }

    /**
     * 转换子主题DTO
     */
    private ThemeDTO.SubThemeDTO convertToSubThemeDTO(EducationTheme subTheme) {
        ThemeDTO.SubThemeDTO dto = new ThemeDTO.SubThemeDTO();
        dto.setId(subTheme.getId());
        dto.setName(subTheme.getName());
        dto.setLabel(subTheme.getLabel());
        dto.setDescription(subTheme.getDescription());
        dto.setCoverImage(subTheme.getCoverImage());
        dto.setSortOrder(subTheme.getSortOrder());
        return dto;
    }

    /**
     * 验证创建子主题请求
     */
    private void validateCreateSubThemeRequest(CreateSubThemeRequest request) {
        if (request.getParentId() == null) {
            throw new IllegalArgumentException("父主题ID不能为空");
        }
        if (request.getName() == null || request.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("子主题名称不能为空");
        }
    }

    /**
     * 验证父主题ID
     */
    private void validateParentId(Long parentId) {
        if (parentId == null || parentId <= 0) {
            throw new IllegalArgumentException("父主题ID无效");
        }
    }

    /**
     * 构建子主题实体
     */
    private EducationTheme buildSubThemeEntity(CreateSubThemeRequest request, EducationTheme parentTheme) {
        EducationTheme subTheme = new EducationTheme();
        subTheme.setParent(parentTheme);
        subTheme.setName(request.getName());
        subTheme.setLabel(request.getLabel() != null ? request.getLabel() : request.getName());
        subTheme.setDescription(request.getDescription());
        subTheme.setCoverImage(request.getCoverImage());
        subTheme.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0);
        return subTheme;
    }
}
